<template>
  <div class="consultation">
    <h2>发血记录</h2>
    <div class="consultation-block">
      <el-button type="primary" size="mini" @click="openDialog('add')">发血</el-button>
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="no" label="住院号"> </el-table-column>
          <el-table-column prop="room" label="病房"> </el-table-column>
          <el-table-column prop="username" label="患者姓名"> </el-table-column>
          <el-table-column prop="phone" label="患者电话"> </el-table-column>
          <el-table-column prop="desc" label="检查结果"> </el-table-column>
          <el-table-column prop="group" label="需要血型"> </el-table-column>
          <el-table-column prop="volume" label="需要容量"> </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                v-if="scope.row.username !== 'admin'"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <h4>请输入住院号</h4>
        <div class="flex-center">
          <el-input size="mini" :disabled="dialogTitle === '编辑'" v-model="no" placeholder="请输入"></el-input>
          <el-button size="mini" type="primary" @click="queryRecord">查询</el-button>
        </div>
      </div>
      <el-form
        :model="form"
        v-if="form"
        status-icon
        ref="form"
        size="mini"
        label-width="120px"
        class="demo-form"
      >
        <el-form-item label="病房" prop="room" style="margin-bottom: 10px;">
          {{form.room}}
        </el-form-item>
        <el-form-item label="患者姓名" prop="username" style="margin-bottom: 10px;">
          {{form.username}}
        </el-form-item>
        <el-form-item label="患者电话" prop="phone" style="margin-bottom: 10px;">
          {{form.phone}}
        </el-form-item>
        <el-form-item label="检查结果" prop="phone" style="margin-bottom: 10px;">
          {{form.desc}}
        </el-form-item>
        <el-form-item label="需要血型" prop="group" style="margin-bottom: 10px;">
          {{form.group}}
        </el-form-item>
        <el-form-item label="需要容量" prop="volume" style="margin-bottom: 10px;">
          {{form.volume}}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="form && form.distribute === 'false'" type="danger" @click="submitForm()">发 血</el-button>
        <el-button v-if="form && form.distribute === 'true'" type="text">已发血</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { getRecord, deleteRecord, updateRecord, getBlood, updateBlood } from "../service.js";
export default {
  name: "home",
  mounted() {
    this.refreshTable();
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      no: '',
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: null,
      bloodList: []
    };
  },
  methods: {
    openDialog(type, row = {}) {
      if (type === 'add') {
        this.dialogTitle = "添加";
        this.form = null
      } else {
        this.dialogTitle = "编辑";
        this.form = row;
      }
      this.isVisible = true;
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.currentPage = index
      this.refreshTable()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "添加") {
            // 库存够不够
            let totalList = this.bloodList.filter(v => (v.group === this.form.group) && (v.status === '已制备' || v.status == '已出库'))
            let total = this.bloodList.filter(v => (v.group === this.form.group) && (v.status === '已制备' || v.status == '已出库'))
            total = total.reduce((a, b) => {
              return a + Number(b.volume.split("m")[0]);
            }, 0)
            let used = this.bloodUsed.filter(v => (v.group === this.form.group)).reduce((a, b) => {
              return a + Number(b.volume.split("m")[0]);
            }, 0)
            if (total - used < Number(this.form.volume.split("m")[0])) {
              this.$message.error('库存不足，无法发血！')
              return
            }
            // 需要更新blood表的status
            // 
            let over = false;
            let need = Number(this.form.volume.split("m")[0])
            if (need === 200 && totalList.filter(v => v.volume === '200ml').length) {
              updateBlood(totalList.filter(v => v.volume === '200ml')[0].id, {
                status: '已出库'
              }).then(res => {
              })
            }
            if (need === 200 && !totalList.filter(v => v.volume === '200ml').length) {
              over = true
              updateBlood(totalList.filter(v => v.volume === '400ml')[0].id, {
                status: '已出库'
              }).then(res => {
              })
            }
            if (need === 400 && totalList.filter(v => v.volume === '400ml').length) {
              updateBlood(totalList.filter(v => v.volume === '400ml')[0].id, {
                status: '已出库'
              }).then(res => {
              })
            }
            if (need === 400 && !totalList.filter(v => v.volume === '400ml').length) {
              updateBlood(totalList.filter(v => v.volume === '200ml')[0].id, {
                status: '已出库'
              }).then(res => {
              })
              updateBlood(totalList.filter(v => v.volume === '200ml')[1].id, {
                status: '已出库'
              }).then(res => {
              })
            }
            let params = {
              distribute: 'true'
            }
            if (over) {
              params.volume = '400ml'
            }
            updateRecord(this.form.id, params).then(res => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.refreshTable();
                this.isVisible = false;
              } else {
                this.$message.error(res.msg || '操作失败');
              }
            })
            return
          }
        } else {
          return false;
        }
      });
    },
    addData() {
      this.dialogTitle = "新增";
      this.isVisible = true;
    },
    refreshTable() {
      getBlood({
        page: 1,
        pageSize: 1000000
      }).then(res => {
        this.bloodList = res.data.data;
      })
      getRecord({
        page: this.currentPage,
        pageSize: this.pageSize,
        distribute: 'true'
      }).then((res) => {
        console.log(res.data)
        this.tableData = res.code === 200 && res.data.data ? res.data.data : [];
        this.total = res.data.total || 0
      });
    },
    updateData(row) {
      this.form = {
        ...row
      };
      this.dialogTitle = "修改";
      this.isVisible = true;
    },
    distribute(row) {
      if (row.distribute === 'true') {
        return '已发血'
      } else {
        return '未发血'
      }
    },
    queryRecord() {
      getRecord({
        page: this.currentPage,
        pageSize: this.pageSize,
        no: this.no
      }).then((res) => {
        console.log(res)
        if (res.data.data.length) {
          this.form = res.data.data[0]
          if (this.form.group) {
            getRecord({
              page: 1,
              pageSize: 10000000,
              form: this.form.group,
              distribute: 'true'
            }).then((rs) => {
              console.log(rs)
              this.bloodUsed = rs.data.data
            })
          }
        } else {
          this.$message.error('住院号有误')
        }
      });
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRecord(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
.flex-center {
  display: flex;
  align-items: center;
  gap: 20px;
  margin: 10px 0px;
}
</style>
